package com.sup.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Reference;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sup.common.Json;
import com.sup.common.Message;
import com.sup.model.Customer;
import com.sup.model.ProductionType;
import com.sup.service.ProductionTypeService;

/**
 * 
 * @author SKH
 *
 */
@Controller
@RequestMapping(value = "/productionType")
public class ProductionTypeController {
	@Autowired
	ProductionTypeService typeService;
	@RequestMapping(value="/save")
	@ResponseBody
	public String saveCustomer(ProductionType productionType){
		Json json=new Json();
		typeService.saveProductionType(productionType);
		json.setMsg("添加商品类型成功");
		json.setSuccess(true);
		return new Message(json).writeJson();
	}
	
	@RequestMapping(value="/update")
	@ResponseBody
	public String updateCustomer(ProductionType productionType){
		Json json=new Json();
		ProductionType productionType2=typeService.findProductionType(productionType.getId());
		if(productionType2.compareTo(productionType)){
			typeService.saveProductionType(productionType);
			json.setSuccess(true);
			json.setMsg("修改商品类型成功");
		}else{
			json.setMsg("修改失败");
		}
		return new Message(json).writeJson();
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public String deleteCustomer(Long id){
		Json json=new Json();
		typeService.removeProductionType(id);
		json.setSuccess(true);
		json.setMsg("删除商品类型成功");
		return new Message(json).writeJson();
	}
	/**
	 * 得到数据列表
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public String findAll(
			@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows") Integer rows) {
		int pageIndex=page-1;
		Page<ProductionType> productionTypepPage=typeService.getProductionTypePage(pageIndex, rows);
		Iterator<ProductionType> iterator=productionTypepPage.iterator();
		List<ProductionType> types=new ArrayList<ProductionType>();
		while(iterator.hasNext()){
			types.add(iterator.next());
		}
		int total=(int) productionTypepPage.getTotalElements();
		return new Message(total,types).toJson();
	}	
	
	@RequestMapping(value="/typeNames")
	@ResponseBody
	public String getTypeNames(){
		List<ProductionType> types=typeService.findAll();
		Iterator<ProductionType> iterator=types.iterator();
		List<ProductionTypeNameBean> typeNames=new ArrayList<ProductionTypeNameBean>();
		while(iterator.hasNext()){
			typeNames.add(new ProductionTypeNameBean(iterator.next()));
		}
		return new Message(typeNames).writeJson();
	}

}
